#include "thread_static.h"

CThreadStatic::CThreadStatic()
{
    m_hThread = (THREAD_HANDLE)0;
#ifdef _WIN32
    m_idThread = 0;
#endif
}

CThreadStatic::~CThreadStatic()
{}

#ifdef _WIN32
    DWORD WINAPI CThreadStatic::_ThreadEntry(LPVOID pParam)
#else
    void* CThreadStatic::_ThreadEntry(void* pParam)
#endif
{
    CThreadStatic* pThread = (CThreadStatic*)pParam;
    if (pThread->initInstance()) {
        pThread->run();
    }
    pThread->exitInstance();

    return NULL;
}

bool CThreadStatic::create()
{
    if (m_hThread != (THREAD_HANDLE)0) {
        return true;
    }

    bool ret = true;
#ifdef _WIN32
    m_hThread = ::CreateThread(NULL, 0, _ThreadEntry, this, 0, &m_idThread);
    if (m_hThread == NULL) {
        ret = false;
    }
#else
    ret = (::pthread_create(&m_hThread, NULL, &_ThreadEntry, this) == 0);
#endif

    return ret;
}

bool CThreadStatic::initInstance()
{
    return true;
}

void CThreadStatic::exitInstance()
{}

void CThreadStatic::osSleep(int nSeconds)
{
#ifdef _WIN32
    ::Sleep(nSeconds * 1000);
#else
    ::Sleep(nSeconds)
#endif // _WIN32
}

void CThreadStatic::sleepMs(int nMilliSeconds)
{
#ifdef _WIN32
    ::Sleep(nMilliSeconds);
#else
    ::usleep(nMilliSeconds);
#endif
}

THREAD_HANDLE CThreadStatic::getHandle()
{
    return m_hThread;
}

bool CThreadStatic::isCurrentThread()
{
#ifdef _WIN32
    return ::GetCurrentThreadId() == m_idThread;
#else
    return ::pthread_self() == m_hThread;
#endif
}

bool CThreadStatic::join()
{
    THREAD_HANDLE hThread = getHandle();
    if (hThread == (THREAD_HANDLE)0) {
        return true;
    }

#ifdef _WIN32
    return (::WaitForSingleObject(hThread, INFINITE) != 0);
#else
    return (::pthread_join(hThread, NULL) == 0);
#endif
}

void CThreadStatic::exitThread()
{
#ifdef _WIN32
    ::ExitThread(0);
#endif
}















